package sing.core.ext.view

import android.graphics.Bitmap
import android.graphics.Canvas
import android.widget.ScrollView
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

/**
 * 获取ScrollView的图片
 */
fun ScrollView.getBitmap(path:String) : Bitmap? {
    var h = 1
    var bitmap: Bitmap? = null
    // 获取listView实际高度
    for (i in 0 until this.childCount) {
        h += this.getChildAt(i).height
    }
    if (h > 1){
        h -= 1
    }
    // 创建对应大小的bitmap
    bitmap = Bitmap.createBitmap(this.getWidth(), h, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    this.draw(canvas)
    // 测试输出
    var out: FileOutputStream? = null
    try {
        out = FileOutputStream(path)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    }
    try {
        if (null != out) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            out.flush()
            out.close()
            return bitmap
        }
    } catch (e: IOException) {
        return null
    }
    return null
}
